/*
 Ubuntu
  $ sudo apt install libcurl4-openssl-dev
  $ sudo find / -name *curl.so
    /usr/lib/x86_64-linux-gnu/libcurl.so
  $ gcc -o demo0 libcurl_demo0.c -lcurl
  $ ./demo0 https://www.taobao.com/help/getip.php
    ipCallback({ip:"122.224.140.87"})
                    |____________|
                           |
                           +------------------------------------+
                                                                |
                                                           ____________
                                                          |            |
  $ ./demo0 http://ip.taobao.com/service/getIpInfo.php?ip=122.224.140.87
    {
      "code":0,
      "data":{
        "ip":"122.224.140.87",
        "country":"中国",
        "area":"",
        "region":"浙江",
        "city":"杭州",
        "county":"XX",
        "isp":"电信",
        "country_id":"CN",
        "area_id":"",
        "region_id":"330000",
        "city_id":"330100",
        "county_id":"xx",
        "isp_id":"100017"
      }
    }
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

struct string {
  char *ptr;
  size_t len;
  int  bytes;
};

void init_string(struct string *s) {
  s->len = 0;
  s->ptr = malloc(s->len+1);
  if (s->ptr == NULL) {
    fprintf(stderr, "malloc() failed\n");
    exit(EXIT_FAILURE);
  }
  s->ptr[0] = '\0';
}

size_t writefunc(void *ptr, size_t size, size_t nmemb, struct string *s)
{
  size_t new_len = s->len + size*nmemb;
  s->ptr = realloc(s->ptr, new_len+1);
  if (s->ptr == NULL) {
    fprintf(stderr, "realloc() failed\n");
    exit(EXIT_FAILURE);
  }
  memcpy(s->ptr+s->len, ptr, size*nmemb);
  s->ptr[new_len] = '\0';
  s->len = new_len;
  s->bytes = size*nmemb;
  //printf("[DEBUG] server reply %d bytes.\n", s->bytes);
  return s->bytes;
}

int main(int argc, char* argv[])
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    struct string s;
    init_string(&s);

    curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    res = curl_easy_perform(curl);

    printf("%s\n", s.ptr);
    printf("[DEBUG] server reply %d bytes.\n", s.bytes);
    free(s.ptr);

    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  return 0;
}
